<?php

/*
 * This file is part of the sfMediaBrowser package.
 *
 * (c) 2009 Vincent Agnano <vincent.agnano@particul.es>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 *
 * @package sfMediaBrowser
 * @author Vincent Agnano <vincent.agnano@particul.es>
 *
 */
class MediaBrowserUtils {

    protected $type_extension = array(
        'document' => array('doc', 'xls', ''),
    );
    public static $icons_path;

    static public function getTypeFromExtension($extension) {
        $extension = self::cleanString($extension);
        $types = self::getFileTypes();
        foreach ($types as $type => $data) {
            if (in_array($extension, $data['extensions'])) {
                return $type;
            }
        }
        return 'file';
    }

    static public function getIconFromType($type) {
        $types = self::getFileTypes();
        $dir = self::getIconsDir();
        if (array_key_exists($type, $types)) {
            $icon = array_key_exists('icon', $types[$type]) ? $types[$type]['icon'] : $type
            ;
            return $dir . '/' . $icon . '.png';
        }
        return $dir . '/file.png';
    }

    static public function getNameFromFile($file) {
        $dot_position = strrpos($file, '.');
        return $dot_position ? substr($file, 0, $dot_position) : $file;
    }

    static public function getExtensionFromFile($file) {
        return strtolower(substr(strrchr($file, '.'), 1));
    }

    static public function getIconFromExtension($extension) {
        $dir = '/sfMediaBrowserPlugin/images/icons';
        $path = self::getIconsPath();
        if (file_exists($path . '/' . $extension . '.png')) {
            return $dir . '/' . $extension . '.png';
        }


        return self::getIconFromType(self::getTypeFromExtension($extension));
    }

    static public function getTypeFromMime($file) {

    }

    static public function getFileTypes() {
        return sfConfig::get('app_sf_media_browser_file_types', array());
    }

    /**
     * Clean a string : lower cased and trimmed
     * @param string string to clean
     * @return string cleaned string
     */
    static public function cleanString($value) {
        return strtolower(trim($value));
    }

    static public function getIconsPath() {
        if (!self::$icons_path) {
            self::$icons_path = sfConfig::get('sf_web_dir') . self::getIconsDir();
        }
        return self::$icons_path;
    }

    static public function getIconsDir() {
        return '/sfMediaBrowserPlugin/images/icons';
    }

    static public function deleteRecursive($path) {
        $files = sfFinder::type('file')->in($path);
        foreach ($files as $file) {
            unlink($file);
        }
        $dirs = array_reverse(sfFinder::type('dir')->in($path));
        foreach ($dirs as $dir) {
            rmdir($dir);
        }
        return @rmdir($path);
    }

    /**
     * Loads js and css files to the response. This is an abstraction layer
     * for no dependency of sfAssetsManagerPlugin
     * @see sfAssetsManagerPlugin
     * @param string $package package name to load
     * @param sfWebResponse optional. Context Response by default
     */
    static public function loadAssets($package, sfWebResponse $response = null) {
        $response = $response ? $response : sfContext::getInstance()->getResponse();

        // sfAssetsManager
        if (class_exists('sfAssetsManager')) {
            $manager = sfAssetsManager::getInstance();
            $manager->load(sprintf('sfMediaBrowser.%s', $package));
        }
        // app.yml configuration
        else {
            $config = sfConfig::get(sprintf('app_sf_media_browser_assets_%s', $package));
            if (isset($config['js']) && !empty($config['js'])) {
                foreach ((array) $config['js'] as $js) {
                    $response->addJavascript($js);
                }
            }
            if (isset($config['css']) && !empty($config['css'])) {
                foreach ((array) $config['css'] as $css) {
                    $response->addStylesheet($css);
                }
            }
        }
    }

    public static function upload(sfWebRequest $request, $root_path = '/') {
        // Settings
        $targetDir = str_replace('//', '/',str_replace('\\', '/', $root_path));
        $maxFileAge = 60 * 60; // Temp file age in seconds
        // 5 minutes execution time
        @set_time_limit(5 * 60);
        // usleep(5000);
        // Get parameters
        $rchunk = $request->getParameter("chunk");
        $rchunks = $request->getParameter("chunks");
        $rname = $request->getParameter("name");
        $chunk = isset($rchunk) ? $rchunk : 0;
        $chunks = isset($rchunks) ? $rchunks : 0;
        $fileName = isset($rname) ? $rname : '';

        // Clean the fileName for security reasons
        $fileName = preg_replace('/[^\w\._]+/', '', $fileName);

        // Make sure the fileName is unique
        if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
            $ext = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);

            $count = 1;
            while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
                $count++;

            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }

        // Create target dir
        if (!file_exists($targetDir))
            @mkdir($targetDir, 0755, true);

        // Look for the content type header
        if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];

        if (isset($_SERVER["CONTENT_TYPE"]))
            $contentType = $_SERVER["CONTENT_TYPE"];

        if (strpos($contentType, "multipart") !== false) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = fopen($_FILES['file']['tmp_name'], "rb");

                    if ($in) {
                        while ($buff = fread($in, 4096))
                            fwrite($out, $buff);
                    } else {
                       return array("jsonrpc"=>"2.0", "result"=>"error", "message"=>"Failed to open input stream.", "filename"=>$fileName);
                    }

                    fclose($out);
                    fclose($in);
                    unlink($_FILES['file']['tmp_name']);
                } else {
                  return json_encode(array("jsonrpc"=>"2.0", "result"=>"error", "message"=>"Failed to open output stream.", "filename"=>$fileName));
                }
            } else {
              return array("jsonrpc"=>"2.0", "result"=>"error", "message"=>"Failed to move uploaded file.", "filename"=>$fileName);
            }
        } else {
            $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = fopen("php://input", "rb");

                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                } else {
                    return array("jsonrpc"=>"2.0", "result"=>"error", "message"=>"Failed to open input stream.", "filename"=>$fileName);
                }

                fclose($out);
                fclose($in);
//                if(sfConfig::get('app_sf_media_browser_thumbnails_enabled', false) && self::getTypeFromExtension(pathinfo($fileName, PATHINFO_EXTENSION)) == 'image')
//                {
//                    self::generateThumbnail($_FILES['file']['tmp_name'], $fileName, $targetDir);
//                }
                unlink($_FILES['file']['tmp_name']);
            } else {
                return array("jsonrpc"=>"2.0", "result"=>"error", "message"=>"Failed to open output stream.", "filename"=>$fileName);
            }
        }
        return array("jsonrpc"=>"2.0", "result"=>"success", "filename"=>$fileName);
    }

    /**
     * @TODO
     * @param $file
     */
    public static function generateThumbnail($source_file, $destination_name, $destination_dir) {
        if (!class_exists('sfImage')) {
            throw new sfException('sfImageTransformPlugin must be installed in order to generate thumbnails.');
        }
        $thumb = new sfImage($source_file);
        $thumb->thumbnail(sfConfig::get('app_sf_media_browser_thumbnails_max_width', 64),
                sfConfig::get('app_sf_media_browser_thumbnails_max_height', 64));
        $destination_dir = $destination_dir . '/' . sfConfig::get('app_sf_media_browser_thumbnails_dir');
        if (!file_exists($destination_dir)) {
            mkdir($destination_dir);
            chmod($destination_dir, 0777);
        }
        return $thumb->saveAs($destination_dir . '/' . $destination_name, 'image/png');
    }

    

    public static function createDirectory(sfWebRequest $request, $root_path = '/') {
        $directory = $request->getParameter('directory');
//        if (preg_match('/windows/i', $_SERVER['HTTP_USER_AGENT'])) {
//            $targetDir = $root_path . '\\' . str_replace("/", "\\", $directory['directory']) .  '\\' .$directory['name'];
//        } else {
//            $targetDir = $root_path . '/' . $directory['directory'] .  '/' .$directory['name'];
//        }
        $targetDir = $root_path . DIRECTORY_SEPARATOR . $directory['directory'] .  '/' .$directory['name'];
        $new_dir = $targetDir;

        $created = @mkdir($new_dir);
        @chmod($new_dir, 0777);
        return 'Directory created!';
    }
}